/*Author: Yuan Li
 *Course:15123-lab1
 *Last Modified Date:May 22 2011
 */

# include "stdio.h"
# include "stdlib.h"
# include "string.h"

int main(int argc,char **argv)
{
	FILE *input,*output;
	/*char valC,space;
	 */
	short valS;
	int ret;

	if (argc < 3){
		printf("You must input input and output file name!\n");
		exit(EXIT_FAILURE);
	} 
	
	/* fopen returns a pointer to the file, otherwise returns
	 * NULL pointer. notice: the NULL pointer is a litter bit
	 * different than 0, NULL is full size of the machine, but 0
	 * may be not
	 */
	if (!(input = fopen(argv[1],"rt"))){
		printf("fail to open %s\n",argv[1]);
		exit(EXIT_FAILURE);
	}

	if (!(output = fopen(argv[2],"wb"))){
		printf("fail to open %s\n",argv[2]);
		exit(EXIT_FAILURE);
	}

	printf("writng from %s to %s ...\n",argv[1],argv[2]);
	
	/*fscanf will return number of success input
	 *if fscanf return not 1 value, it indicates maybe reach 
	 *the end of the file
	 */
	 while((fscanf(input,"%hi",&valS))== 1){
		/* "%hi" means short int
		 *printf("%hi\n",valS);
		 *ferror will detect file i/o error by the file stream
		 *fwrite returns number of success output
		 */
		ret = fwrite(&valS,sizeof(valS),1,output);
		if (ret != 1){
			if (ferror(output))
				printf("I/O error encountered(fwrite)\n");
			else 
				printf("unknow error(fwrite)\n");
			exit(EXIT_FAILURE);
		}
	}

	fclose(input);
	fclose(output);

	printf("writing done\n");

	printf("reading from %s ...\n",argv[2]);

	if (!(output = fopen(argv[2],"rb"))){
		printf("fail to open %s\n",argv[2]);
		exit(EXIT_FAILURE);
	}

	while(1){
		ret = fread(&valS,sizeof(valS),1,output);

		if (ret != 1){
			if(feof(output))
				break;
			else if (ferror(output))
				printf("I/O error(fread)\n");
			else
				printf("unknow error(fread)\n");
			
			exit(EXIT_FAILURE);
		}
		
		printf("%hi\n",valS);
	}		
			
	return 0;
		
}
